
package pos.control;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import pos.Pos;
import pos.entity.Promotion;
import pos.storage.db.sql.SQL;

/**
 * The control object for the promotion entity
 * @author Justin Hume
 */
public class PromotionControl {

    /**
     * Adds a new promotion to the repository
     * @param promo
     * @return a boolean indicating success or failure
     */
    public boolean add(Promotion promo){
        try{   
            //Set parameters in the prepared statement, in the following order:
            //  PromotionName
            //  PromotionDescription
            //  PromotionConditions
            //  PromotionType
            //  PromotionPriceAdjustment
            //  PromotionCreatedByEmployeeId
            //  PromotionStartDateTime
            //  PromotionEndDateTime
            //  DateTimeCreated
            //  DateTimeModified

            //Obtain the prepared statement from the SQL list
            PreparedStatement promoInsertStmt = Pos.adminConn.prepareStatement(SQL.INSERTPROMOTION);

            //Generate new unique Id for the promotion table
            long promoId = pos.util.IDGenerator.getID();

            promoInsertStmt.setLong(1, promoId);
            promoInsertStmt.setString(2, promo.getPromotionName());
            promoInsertStmt.setString(3, promo.getPromotionDescription());
            promoInsertStmt.setString(4, promo.getPromotionConditions());
            
            //using .ordinal() to convert enum to its integer index
            promoInsertStmt.setInt(5, promo.getPromotionType().ordinal());

            promoInsertStmt.setDouble(6, promo.getPromotionPriceAdjustment());
            promoInsertStmt.setLong(7, promo.getPromotionCreatedByEmployeeId());
            promoInsertStmt.setDate(8, promo.getPromotionStartDateTime());
            promoInsertStmt.setDate(9, promo.getPromotionEndDateTime());
            promoInsertStmt.setDate(10, promo.getDateTimeCreated());
            promoInsertStmt.setDate(11, promo.getDateTimeModified());
            
            promoInsertStmt.executeUpdate();

            //Update the list of promotionItems
            PreparedStatement promoItemsInsertStmt = Pos.adminConn.prepareStatement(SQL.INSERTPROMOTIONITEMS);

            
            promoItemsInsertStmt.setString(1, promo.getPromotionName());
            promoItemsInsertStmt.setString(2, promo.getPromotionDescription());
            promoItemsInsertStmt.setDouble(3, promo.getPromotionPriceAdjustment());
            promoItemsInsertStmt.setString(4, promo.getPromotionConditions());
            promoItemsInsertStmt.setDouble(5, promo.getPromotionPriceAdjustment());
            promoItemsInsertStmt.setLong(6, promoId);

            promoItemsInsertStmt.executeUpdate();

            return true;
        }
        catch(SQLException e){
            e.printStackTrace();
            return false;
        }
    }
}
